<template>
  <div class="register-container">
    <div class="bg-img">
      <el-image :src="bgImg" fit="cover" lazy></el-image>
    </div>
    <div class="logo-container">
      <router-link :to="{ path: '/home' }">
        <div class="logo-img">
          <el-image fit="cover" :src="logo"> </el-image>
        </div>
      </router-link>
      <el-divider direction="vertical"></el-divider>
      <span class="sub-title"> 欢迎来到技转云 </span>
    </div>
    <div class="form-container">
      <div v-show="!activeTitle('forgetPassword')" class="form-box">
        <div class="form-title">
          <router-link :to="{ path: '/login' }">
            <span :class="[activeTitle('login') ? 'active' : '']">
              登录
            </span>
          </router-link>

          <el-divider direction="vertical"></el-divider>

          <router-link :to="{ path: '/register' }">
            <span :class="[activeTitle('register') ? 'active' : '']">
              注册
            </span>
          </router-link>
        </div>

        <!-- <el-form-item label="" prop="passwordVerify">
            <el-input
              :disabled="!registerForm.password"
              placeholder="请确认密码"
              show-password
              v-model="registerForm.passwordVerify"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-lock"
                style="font-size: 1.6rem;"
              ></i>
            </el-input>
          </el-form-item> -->

        <el-form
          v-show="activeTitle('register')"
          ref="registerForm"
          :model="registerForm"
          :rules="registerFormRule"
          class="demo-registerForm"
        >
          <el-form-item label="" prop="userName">
            <el-input
              placeholder="用户名: 字母和数字组成(长度4-10)"
              v-model="registerForm.userName"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-user-solid"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
          </el-form-item>
          <el-form-item label="" prop="password">
            <el-input
              minlength="5"
              maxlength="20"
              placeholder="请输入密码(长度5-20)"
              show-password
              v-model="registerForm.password"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-lock"
                style="font-size: 1.6rem;"
              ></i>
            </el-input>
          </el-form-item>

          <el-form-item label="" prop="phonenumber">
            <el-input
              type="number"
              placeholder="请输入手机号"
              v-model="registerForm.phonenumber"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-phone"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
          </el-form-item>
          <el-form-item label="" prop="code" class="code-input">
            <el-input
              type="number"
              maxlength="5"
              placeholder="请输入验证码"
              v-model="registerForm.code"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-s-claim"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
            <div class="verify-btn-container">
              <el-button
                :disabled="isCanGetCode"
                type="primary"
                @click="getCode"
              >
                {{ isGetcode ? countDown : '' }}
                获取验证码
              </el-button>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              :loading="registerLoading"
              :disabled="isCanRegister"
              type="primary"
              @click="submitRegisterForm"
            >
              注册
            </el-button>
          </el-form-item>
        </el-form>

        <el-form
          v-show="activeTitle('login')"
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="demo-registerForm"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              type="text"
              auto-complete="off"
              placeholder="账号"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-user-solid"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              auto-complete="off"
              placeholder="密码"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-lock"
                style="font-size: 1.6rem;"
              ></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="code" class="code-input">
            <el-input
              v-model="loginForm.code"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter.native="handleLogin"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-s-claim"
                style="font-size: 1.6rem;"
              ></i>
            </el-input>
            <div class="verify-btn-container">
              <img
                :src="codeUrl"
                style="height: 48px"
                @click="getCodeNum"
                class="login-code-img"
              />
            </div>
          </el-form-item>
          <el-checkbox
            v-model="loginForm.rememberMe"
            style="margin:0px 0px 25px 0px;"
            >记住密码</el-checkbox
          >
          <el-form-item style="width:100%;">
            <el-button
              :loading="loginLoading"
              size="medium"
              type="primary"
              style="width:100%;"
              @click.native.prevent="handleLogin"
            >
              <span>登 录</span>
            </el-button>
          </el-form-item>
        </el-form>

        <!-- <el-form
          v-show="activeTitle('login')"
          ref="loginForm"
          :model="loginForm"
          :rules="loginFormRule"
          class="demo-loginForm"
        >
          <el-form-item label="" prop="phonenumber">
            <el-input
              type="number"
              placeholder="请输入手机号"
              v-model="loginForm.phonenumber"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-user-solid"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
          </el-form-item>

          <el-form-item label="" prop="password">
            <el-input
              minlength="5"
              maxlength="20"
              type="text"
              placeholder="请输入密码(长度5-20)"
              show-password
              v-model="loginForm.password"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-lock"
                style="font-size: 1.6rem;"
              ></i>
            </el-input>
          </el-form-item>

          <el-form-item>
            <router-link :to="{ path: '/forgetPassword' }">
              <div
                style="height: 20px;color: #1678ff;text-align: right; margin-bottom: 32px"
              >
                忘记密码?
              </div>
            </router-link>
          </el-form-item>

          <el-form-item>
            <el-button
              :loading="loginLoading"
              :disabled="isCanLogin"
              type="primary"
              @click="submitLoginForm"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form> -->
      </div>

      <div v-show="activeTitle('forgetPassword')" class="form-box">
        <div class="form-title flex" style="justify-content: space-between">
          <span class="active">
            找回密码
          </span>

          <router-link :to="{ path: '/login' }">
            <span>
              去登录
            </span>
          </router-link>
        </div>
        <el-form
          ref="updateUserForm"
          :model="updateUserForm"
          :rules="updateUserFormRule"
          class="demo-updateUserForm"
        >
          <el-form-item label="" prop="password">
            <el-input
              minlength="5"
              maxlength="20"
              type="text"
              placeholder="请输入密码(长度5-20)"
              show-password
              v-model="updateUserForm.password"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-lock"
                style="font-size: 1.6rem;"
              ></i>
            </el-input>
          </el-form-item>

          <el-form-item label="" prop="phonenumber">
            <el-input
              type="number"
              placeholder="请输入手机号"
              v-model="updateUserForm.phonenumber"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-phone"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
          </el-form-item>
          <el-form-item label="" prop="code" class="code-input">
            <el-input
              type="number"
              maxlength="5"
              placeholder="请输入验证码"
              v-model="updateUserForm.code"
            >
              <i
                slot="prefix"
                class="el-input__icon el-icon-s-claim"
                style="font-size: 1.6rem"
              ></i>
            </el-input>
            <div class="verify-btn-container">
              <el-button
                :disabled="isCanGetForgetCode"
                type="primary"
                @click="getForgetCode"
              >
                {{ isGetcode ? countDown : '' }}
                获取验证码
              </el-button>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              :loading="updateUserLoading"
              :disabled="isCanUpdate"
              type="primary"
              @click="submitUpdateUser"
            >
              找回密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getVerifyCode,
  registerUser,
  getForgetVerifyCode,
  updatePassword,
} from '@/api/login'

import { getCodeImg } from '@/api/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: 'register',
  computed: {
    activeTitle() {
      return (name) => {
        return name == this.nowRouteName
      }
    },
    isCanGetForgetCode() {
      return !(
        this.updateUserForm.phonenumber
        // this.registerForm.passwordSecond &&
        // this.registerForm.userName &&
        // !this.isGetcode
      )
    },
    isCanGetCode() {
      return !(
        this.registerForm.phonenumber
        // this.registerForm.passwordSecond &&
        // this.registerForm.userName &&
        // !this.isGetcode
      )
    },
    isCanLogin() {
      let formName = 'loginForm'
      let res = true
      if (
        this.loginForm.phonenumber &&
        this.loginForm.password &&
        this.loginForm.code
      ) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            res = false
          } else {
            res = true
          }
        })
      }
      return res
    },
    isCanUpdate() {
      let formName = 'updateUserForm'
      let res = true

      if (this.updateUserForm.phonenumber && this.updateUserForm.password) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            res = false
          } else {
            res = true
          }
        })
      }
      return res
    },
    isCanRegister() {
      let formName = 'registerForm'
      let res = true

      if (
        this.registerForm.phonenumber &&
        this.registerForm.password &&
        this.registerForm.userName &&
        this.registerForm.code
      ) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            res = false
          } else {
            res = true
          }
        })
      }
      return res
    },

    // isCanUpdateUser() {},
  },
  data() {
    var checkuserName = (rule, value, callback) => {
      if (!value) {
        return callback(
          new Error('4~10位字符，可由中文、英文、数字或符号“_”组成')
        )
      }
      if (!/(?!^[a-z]+$)^[a-z][a-z0-9]{3,9}$/gi.test(value)) {
        callback(new Error('用户名格式错误，请输入正确的用户名'))
      } else {
        callback()
      }
    }
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入您的手机号'))
      }
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('格式错误，请输入正确的手机号'))
      } else {
        callback()
      }
    }

    var loginPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('6~20个英文字母、符号或数字组合'))
      } else {
        if (value.length < 5 || value.length > 20) {
          callback(new Error('密码必须由6~20个英文字母、符号或数字组合'))
        }
        // if (this.loginForm.passwordSecond !== '') {
        //   this.$refs.loginForm.validateField('passwordSecond')
        // }
        callback()
      }
    }
    var codePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入您的验证码'))
      } else {
        // if (value.length < 5 || value.length > 20) {
        //   callback(new Error('密码必须由6~20个英文字母、符号或数字组合'))
        // }

        callback()
      }
    }
    //     var registerPass = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请输入密码'))
    //   } else {

    //     callback()
    //   }
    // }
    // var updatePass = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请输入密码'))
    //   } else {

    //     callback()
    //   }
    // }
    // var passwordSecond = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请再次输入密码'))
    //   } else if (value !== this.registerForm.password) {
    //     callback(new Error('两次输入密码不一致!'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      logo: require('@/assets/images/head.png'),

      // bgImg: 'https://w.wallhaven.cc/full/g7/wallhaven-g7mzk3.jpg',
      // bgImg: 'https://w.wallhaven.cc/full/28/wallhaven-28ekym.jpg',
      // bgImg: 'https://w.wallhaven.cc/full/8o/wallhaven-8o975y.jpg',
      bgImg: 'https://w.wallhaven.cc/full/pk/wallhaven-pkyqj3.jpg',
      isGetcode: false,
      countDown: 60,
      nowRouteName: 'login',

      loginLoading: false,
      codeUrl: '',
      cookiePassword: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: '',
      },
      loginRules: {
        username: [{ validator: checkPhone, trigger: 'blur' }],
        password: [{ validator: loginPass, trigger: 'blur' }],
        code: [{ validator: codePass, trigger: 'blur', required: true }],
      },

      registerFormRule: {
        userName: [{ validator: checkuserName, trigger: 'blur' }],
        phonenumber: [{ validator: checkPhone, trigger: 'blur' }],
        password: [{ validator: loginPass, trigger: 'blur' }],
        code: [{ validator: codePass, trigger: 'blur', required: true }],
      },
      registerLoading: false,
      registerForm: {
        userName: '',
        phonenumber: '',
        password: '',
        code: '',
      },

      // loginForm: {
      //   phonenumber: '',
      //   password: '',
      // },
      loginFormRule: {
        phonenumber: [{ validator: checkPhone, trigger: 'blur' }],
        password: [{ validator: loginPass, trigger: 'blur' }],
      },

      updateUserLoading: false,
      updateUserForm: {
        phonenumber: '',
        password: '',
        code: '',
      },
      updateUserFormRule: {
        phonenumber: [{ validator: checkPhone, trigger: 'blur' }],
        password: [{ validator: loginPass, trigger: 'blur' }],
        code: [{ trigger: 'blur', required: true, message: '请输入验证码' }],
      },
    }
  },
  watch: {
    $route(to) {
      this.nowRouteName = to.name
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.nowRouteName = to.name
    })
  },
  created() {
    this.getCodeNum()
    this.getCookie()
  },
  mounted() {
    // this.submitRegisterForm()
    this.enterKeyup()
  },
  destroyed() {
    this.enterKeyupDestroyed()
  },
  methods: {
    getCodeNum() {
      getCodeImg().then((res) => {
        this.codeUrl = 'data:image/gif;base64,' + res.img
        this.loginForm.uuid = res.uuid
      })
    },
    getCookie() {
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      }
    },
    handleLogin() {
      console.log('---------')
      console.log(this.isCanLogin)
      if (this.isCanLogin) {
        return
      }
      console.log('VVVVVVVVVVVVVVV')
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loginLoading = true
          if (this.loginForm.rememberMe) {
            Cookies.set('username', this.loginForm.username, { expires: 30 })
            Cookies.set('password', encrypt(this.loginForm.password), {
              expires: 30,
            })
            Cookies.set('rememberMe', this.loginForm.rememberMe, {
              expires: 30,
            })
          } else {
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('rememberMe')
          }
          this.$store
            .dispatch('Login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/' }).catch(() => {})
            })
            .catch(() => {
              this.loginLoading = false
              this.getCodeNum()
            })
        }
      })
    },

    // 获取电话验证码
    getCode() {
      // 调用方法后 isGetcode  转为 true
      let phone = this.registerForm.phonenumber
      getVerifyCode(phone).then((res) => {
        if (res.code == 200) {
          this.isGetcode = true
          this.countDownFun()
          phone = null
        }
      })
    },
    countDownFun() {
      if (this.countDown == 60) {
        let setTimeDo = null
        let that = this
        setTimeDo = setInterval(() => {
          that.countDown--

          if (that.countDown == 0) {
            if (setTimeDo) {
              this.countDown = 60
              clearInterval(setTimeDo)
              that.isGetcode = false
            }
          }
        }, 1000)
      }
    },
    enterKey(event) {
      const componentName = this.$options.name
      if (componentName == 'register') {
        const code = event.keyCode
          ? event.keyCode
          : event.which
          ? event.which
          : event.charCode
        if (code == 13) {
          if (this.activeTitle('register')) {
            this.submitRegisterForm()
          }
          if (this.activeTitle('login')) {
            this.submitLoginForm()
          }
          if (this.activeTitle('forgetPassword')) {
            this.submitUpdateUser()
          }
        }
      }
    },
    enterKeyupDestroyed() {
      document.removeEventListener('keyup', this.enterKey)
    },
    enterKeyup() {
      document.addEventListener('keyup', this.enterKey)
    },

    submitRegisterForm() {
      if (this.isCanRegister) {
        return
      }
      let formName = 'registerForm'
      let that = this
      this.$refs[formName].validate((valid) => {
        this.registerLoading = true
        if (valid) {
          let data = that.registerForm
          registerUser(data).then((res) => {
            if (res.code == 200) {
              that.$message({
                type: 'success',
                message: '注册成功',
              })
              setTimeout(() => {
                this.registerLoading = false
                that.$refs[formName].resetFields()
                that.$router.push({ path: '/login' })

                that = null
                formName = null
                data = null
              }, 2000)
            }
          })
        }
      })
    },
    submitLoginForm() {
      let formName = 'loginForm'

      this.$refs[formName].validate((valid) => {
        this.loginLoading = true

        if (valid) {
          console.log('')
        }
      })
    },

    getForgetCode() {
      let phone = this.updateUserForm.phonenumber
      getForgetVerifyCode(phone).then((res) => {
        if (res.code == 200) {
          this.isGetcode = true
          this.countDownFun()
          phone = null
        }
      })
    },
    // 找回密码
    submitUpdateUser() {
      let formName = 'updateUserForm'
      let that = this
      this.$refs[formName].validate((valid) => {
        this.updateUserLoading = true
        if (valid) {
          let data = that.updateUserForm
          updatePassword(data).then((res) => {
            if (res.code == 200) {
              that.$message({
                type: 'success',
                message: '修改成功,为您跳转至登录',
              })
              setTimeout(() => {
                this.updateUserLoading = false
                that.$refs[formName].resetFields()
                that.$router.push({ path: '/login' })

                that = null
                formName = null
                data = null
              }, 1000)
            }
          })
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.register-container {
  position: relative;
  width: 100%;
  height: 100vh;
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  background-color: #efefef;

  .bg-img {
    position: absolute;
    z-index: 10;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    .el-image {
      width: 100%;
      height: 100%;
    }
  }

  .logo-container {
    z-index: 100;
    display: flex;
    align-items: center;
    height: 52px;
    width: 1200px;
    margin-bottom: 52px;
    font-size: 28px;

    .logo-img {
      height: 52px;
      width: 200px;

      .el-image {
        width: 100%;
        height: 100%;
      }
    }
    .sub-title {
      font-family: Source Han Sans CN, Source Han Sans CN-Medium;
      font-weight: 500;
      text-align: left;
      color: #999999;
    }
  }

  @keyframes form-animation {
    0% {
      transform: translateY(30px);
    }
    25% {
      transform: translateY(22px);
    }
    50% {
      transform: translateY(15px);
    }
    75% {
      transform: translateY(8px);
    }
    100% {
      transform: translateY(0px);
    }
  }
  @keyframes form-opacity {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }

  .form-container {
    z-index: 100;
    display: flex;
    align-items: center;
    width: 1200px;
    height: 700px;
    border-radius: 10px;
    background-color: #fff;
    box-shadow: 0 0 15px #979797;
    transform: translateY(0px);
    animation: form-animation 400ms ease;

    .form-box {
      height: 100%;
      width: 366px;
      margin-left: 731px;
      opacity: 0;
      animation: form-opacity 800ms ease 200ms;
      animation-fill-mode: forwards;
      // border: 1px solid #f0f;
      .form-title {
        font-size: 20px;
        font-family: Source Han Sans CN, Source Han Sans CN-Medium;
        margin: 123px 0 66px 0;

        .active {
          font-size: 24px;
          font-weight: 500;
          text-align: left;
          color: #1678ff;
        }
      }

      .el-form {
        width: 366px;

        ::v-deep.el-input {
          input[type='number'] {
            -moz-appearance: textfield;
          }
          input[type='number']::-webkit-inner-spin-button,
          input[type='number']::-webkit-outer-spin-button {
            -webkit-appearance: none;
            margin: 0;
          }

          .el-input__inner {
            height: 48px;
            line-height: 48px;
            border-radius: 4px;
            padding-left: 50px;
          }
          .el-input__prefix {
            padding: 0 10px;
          }
        }

        .code-input {
          ::v-deep .el-form-item__content {
            display: flex;

            justify-content: space-between;
            width: 100%;
          }
          ::v-deep .el-input {
            min-width: 60%;
            // width: 200px;
            // height: 48px;
            // line-height: 48px;
            // padding-right: 0;
            input[type='number'] {
              -moz-appearance: textfield;
            }
            input[type='number']::-webkit-inner-spin-button,
            input[type='number']::-webkit-outer-spin-button {
              -webkit-appearance: none;
              margin: 0;
            }
            .el-input__inner {
              border-radius: 4px 0 0 4px;
              // border-radius: 0;
              // border-width: 0 0 1px 0;
            }
          }

          .verify-btn-container {
            min-width: 40%;

            .el-button {
              border-radius: 0 4px 4px 0;
              // border-radius: 10px;
            }
          }
        }

        .el-button {
          height: 48px;
          width: 100%;
          font-size: 18px;
          border-radius: 4px;
        }
      }
    }
  }
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}
::v-deep .el-input {
  display: flex;
  align-items: center;
}
.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
</style>
